﻿/*********************************************************************************
**                                                                              **
**  Copyright (C) 2022-2022 LiLong                                              **
**  This file is part of BluetoothCpp.                                          **
**                                                                              **
**  BluetoothCpp is free software: you can redistribute it and/or modify        **
**  it under the terms of the GNU Lesser General Public License as published by **
**  the Free Software Foundation, either version 3 of the License, or           **
**  (at your option) any later version.                                         **
**                                                                              **
**  BluetoothCpp is distributed in the hope that it will be useful,             **
**  but WITHOUT ANY WARRANTY; without even the implied warranty of              **
**  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the               **
**  GNU Lesser General Public License for more details.                         **
**                                                                              **
**  You should have received a copy of the GNU Lesser General Public License    **
**  along with BluetoothCpp.  If not, see <https://www.gnu.org/licenses/>.      **
**********************************************************************************/
#pragma once

#include <stdlib.h>
#include <string>

#ifdef WIN32
#include <Windows.h>
#endif

namespace BTH
{
#ifdef WIN32
static std::string WCharToMByte(const wchar_t* str, DWORD dwSize)
{
    DWORD dwMinSize = WideCharToMultiByte(CP_ACP, NULL, str, dwSize, NULL, 0, NULL, FALSE);
    std::string buffer(dwMinSize, '0');
    WideCharToMultiByte(CP_ACP, NULL, str, dwSize, buffer.data(), dwMinSize, NULL, FALSE);
    return buffer;
}
#endif

inline std::string fromWChart(const wchar_t* str, size_t size)
{
#ifdef WIN32
    return WCharToMByte(str, static_cast<DWORD>(size));
#else
    if (!str || !size)
        return {};
    std::mbstate_t stat;
    size_t len = 0;
    auto err   = wcsrtombs_s(&len, nullptr, 0, &str, size, &stat);
    if (err != 0)
        return {};
    std::string buffer(len, '0');
    wcsrtombs_s(&len, buffer.data(), len, &str, size, &stat);
    buffer.resize(buffer.size() - 1);
    return buffer;
#endif
}
} // namespace BTH
